package com.github.hgkmail.hello.leetcode101.pointer.tree;

import com.github.hgkmail.hello.leetcode101.base.CommonUtil;
import com.github.hgkmail.hello.leetcode101.base.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class LC637AverageOfLevelsInBinaryTree {
    public List<Double> averageOfLevels(TreeNode root) {
        if (root==null) {
            return new ArrayList<>();
        }
        List<Double> res=new ArrayList<>();
        //层次遍历
        Queue<TreeNode> queue = new LinkedList();
        queue.offer(root);
        int level=0;
        int len=0, count;
        double sum;
        while (!queue.isEmpty()) {
            len=queue.size();
            level++;
            sum=0.0d;
            count=len;
            while (len>0) {
                len--;
                TreeNode node = queue.poll();
                sum+=node.val;
                if (node.left!=null) {
                    queue.offer(node.left);
                }
                if (node.right!=null) {
                    queue.offer(node.right);
                }
            }
            res.add(sum/count);
        }

        return res;
    }

    public static void main(String[] args) {
        TreeNode root= CommonUtil.deserializeBinaryTree("3,9,#,#,20,15,#,#,7,#,#");
        System.out.println(new LC637AverageOfLevelsInBinaryTree().averageOfLevels(root));
    }
}
